const express = require('express')
const moment = require('moment')
const db = require('./libs/DBHelper')
const server = express()
server.use(express.static("./../src"))
server.use(express.urlencoded({ extended: false }))
server.use(express.json())

server.all('*', (req, res, next) => {
    res.setHeader('Access-Control-Allow-origin', '*')
    next()
})
server.post('/login', async (req, res) => {
    try {
        let oUser = req.body;
        let sql_login = "SELECT `uId`, `uName`,`uCreatedata` FROM users WHERE uName=? AND uPwd=? AND ustatus=1;"
        const result = await db.exec(sql_login, [oUser.name, oUser.pwd])
        const isLogin = result && result.length >= 1;
        res.json({
            msg: isLogin ? '登陆成功' : '登录失败',
            data: result[0],
            code: isLogin ? 200 : 201
        })
    } catch (error) {
        res.json({
            msg: '登录失败',
            error,
            code: 201
        })
    }

})

server.post('/reg', async (req, res) => {
    try {
        let oUser = req.body;
        let sql_reg = "INSERT INTO `users` (`uName`,`uPwd`,`uCreatedata`)VALUES(?,?,?);"
        let params = [
            oUser.name,
            oUser.pwd,
            moment().format('YYYY-MM-DD HH:mm:ss')
        ]
        const results = await db.exec(sql_reg, params)
        let isReg = results && results.affectedRows >= 1
        res.json({
            msg: isReg ? '注册成功!' : '注册失败!',
            code: isReg ? 200 : 201
        })
    } catch (error) {
        res.json({
            msg: '注册失败!',
            code: 201,
            err
        })
    }

})


server.listen(8080, () => {
    console.log('http://127.0.0.1:8080服务器启动完毕!');
})